package com.feeyo.groundservice.checkin.activity.view

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.SuccessCallbackWithData
import com.feeyo.groundservice.base_util.getConfirmDlg
import com.feeyo.groundservice.base_util.getRouterPath
import com.feeyo.groundservice.checkin.R
import com.feeyo.groundservice.checkin.activity.CheckInPersonSelectActivity
import com.feeyo.groundservice.checkin.constant.CheckInPath
import com.feeyo.groundservice.checkin.constant.checkInUser
import com.feeyo.groundservice.checkin.constant.checkInUserRefreshFlag
import com.feeyo.groundservice.checkin.constant.statusBarColor
import com.feeyo.groundservice.checkin.model.CheckInPerSonBO
import com.feeyo.groundservice.checkin.viewmodel.CheckInViewModel
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.constant.ComposePosition
import com.feeyo.groundservice.composewidget.view.drag_list.list.DragDropLazyColumn
import com.feeyo.groundservice.composewidget.view.sidemenu.ChainScrollableComponentState
import com.feeyo.groundservice.composewidget.view.sidemenu.SlideMenu
import com.feeyo.groundservice.composewidget.view.title_bar.CommonTitleView
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import com.feeyo.groundservice.http.utils.listFromJson

/**
 *作者：70893 on 2025-10-27
 *描述：
 */


@Composable
internal fun CheckInPersonSelectMainView() {

    val viewModel: CheckInViewModel = viewModel()
    val refreshFlag = remember { mutableLongStateOf(System.currentTimeMillis()) }
    val checkInUserList = remember { mutableStateListOf<CheckInPerSonBO>() }
    //侧滑状态
    val states = remember { mutableStateListOf<ChainScrollableComponentState>() }


    Column(
        modifier = Modifier.fillMaxSize().background(R.color.page_color.toComposeColor())
    ) {
        CommonTitleView(
            title = "值机人员设置",
            bg = statusBarColor.toComposeColor(),
            topPadding = BarUtils.getStatusBarHeight(),
            onBack = {
                ActivityUtils.getTopActivity()?.finish()
            },
            rightContent = {
                Text(
                    text = "保存",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W500,
                    color = R.color.white.toComposeColor(),
                    modifier = Modifier.intervalClick {
                        viewModel.saveCheckInUser(checkInUserList, object : SuccessCallback {
                            override fun success() {
                                super.success()
                                //刷新人员
                                checkInUserRefreshFlag.longValue = System.currentTimeMillis()
                                ActivityUtils.getTopActivity()?.finish()
                            }
                        })
                    }
                )
            })

        Row(
            modifier = Modifier.fillMaxWidth().height(R.dimen.d48.dimenToDp())
                .background(Color.White)
                .padding(horizontal = R.dimen.d15.dimenToDp()),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            val title = buildAnnotatedString {
                withStyle(
                    style = SpanStyle(
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_33.toComposeColor().copy(0.55f)
                    )
                ) {
                    append("共")
                }

                withStyle(
                    style = SpanStyle(
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W500,
                        color = statusBarColor.toComposeColor()
                    )
                ) {
                    append(checkInUserList.size.toString())
                }


                withStyle(
                    style = SpanStyle(
                        fontSize = R.dimen.d14.dimenToSp(),
                        fontWeight = FontWeight.W400,
                        color = R.color.black_33.toComposeColor().copy(0.55f)
                    )
                ) {
                    append("人")
                }
            }

            //人数
            Text(text = title)

            Spacer(modifier = Modifier.weight(1f))

            //新增
            Icon(
                painter = R.drawable.icon_add_circle.drawableToPainter(),
                contentDescription = null,
                tint = R.color.gray_88.toComposeColor(),
                modifier = Modifier.size(R.dimen.d24.dimenToDp())
                    .intervalClick {
                        CheckInPath.SelectUserActivity.getRouterPath()
                            .withString("title", "值机选人")
                            .withString("type", "2")//走创建逻辑
                            .withObject("listener", object : SuccessCallbackWithData {
                                override fun success(data: Any) {
                                    super.success(data)
                                    data as List<CheckInPerSonBO>
                                    checkInUserList.addAll(data.filter {
                                        //去重
                                        it.uid !in checkInUserList.map { it.uid }
                                    })
                                    //关闭到当前页面
                                    ActivityUtils.finishToActivity(
                                        CheckInPersonSelectActivity::class.java,
                                        false
                                    )
                                }
                            })
                            .navigation()

//                        checkInUserList.add(CheckInPerSonBO("9", "宋佳慧", "songjiahui"))
//                        checkInUserList.add(CheckInPerSonBO("10", "权良虎", "quanlianghu"))
//                        checkInUserList.add(CheckInPerSonBO("11", "由晓丹", "youxiaodan"))
//                        checkInUserList.add(CheckInPerSonBO("12", "马根节", "magenjie"))
//                        checkInUserList.add(CheckInPerSonBO("13", "付越", "fuyue"))
                    }
            )

            HorizontalSpace(R.dimen.d15.dimenToDp())

            //全部清除
            Icon(
                painter = R.drawable.icon_clear.drawableToPainter(),
                contentDescription = null,
                tint = R.color.gray_88.toComposeColor(),
                modifier = Modifier.size(R.dimen.d24.dimenToDp())
                    .intervalClick {
                        checkInUserList.clear()
                    }
            )
        }

        DragDropLazyColumn(
            modifier = Modifier.fillMaxWidth().weight(1f),
            verticalArrangement = Arrangement.spacedBy(R.dimen.d8.dimenToDp()),
            contentPadding = PaddingValues(
                horizontal = R.dimen.d15.dimenToDp(),
                vertical = R.dimen.d12.dimenToDp()
            ),
            draggable = true,
            items = checkInUserList,
            onDragStart = {},
            onDrag = { from, to ->
                checkInUserList.add(to, checkInUserList.removeAt(from))
            },
            onDragEnd = {},
            itemContent = { modifier, item, isDragging ->
                PersonItemView(
                    modifier = modifier.height(R.dimen.d48.dimenToDp()),
                    isDragging = isDragging,
                    item = item,
                    states = states,
                    onDelete = {
                        checkInUserList.remove(item)
                    })
            }
        )
    }

    //查询配置的人员
    LaunchedEffect(key1 = refreshFlag.longValue) {
        checkInUser?.let {
            checkInUserList.clear()
            checkInUserList.addAll(it)
        }
    }
}

@Composable
internal fun PersonItemView(
    modifier: Modifier,
    isDragging: Boolean,
    item: CheckInPerSonBO,
    states: SnapshotStateList<ChainScrollableComponentState>,
    onDelete: () -> Unit
) {
    val menuWidth = R.dimen.d50.dimenToDp()

    Card(
        modifier = modifier,
        elevation = CardDefaults.elevatedCardElevation(defaultElevation = R.dimen.d5.dimenToDp()),
        shape = RoundedCornerShape(R.dimen.d4.dimenToDp()),
        colors = CardDefaults.elevatedCardColors(
            containerColor = if (isDragging)
                R.color.gray_EE.toComposeColor()
            else
                Color.White
        )
    ) {
        SlideMenu(
            minScrollPosition = 0.dp,
            maxScrollPosition = menuWidth,
            contentIsMove = false,
            composePosition = ComposePosition.End,
            modifier = Modifier.fillMaxWidth().height(R.dimen.d48.dimenToDp()),
            onOpenOrClose = { state ->
                //遍历state，把不是自己的都复原
                states.forEach {
                    if (it != state) {
                        it.setScrollPositionWithAnimate(it.maxPx)
                    }
                }
            },
            backgroundContent = {
                states.add(it)
                Box(
                    modifier = Modifier.width(menuWidth).fillMaxHeight()
                        .background(
                            color = R.color.red_FF3141.toComposeColor()
                        )
                        .intervalClick {
                            //删除
                            onDelete()
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "删除",
                        fontSize = R.dimen.d14.dimenToSp(),
                        color = R.color.white.toComposeColor(),
                    )
                }
            }
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(start = R.dimen.d10.dimenToDp())
                    .intervalClick {
                        it.closeMenu()
                    },
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = item.username,
                    fontSize = R.dimen.d18.dimenToSp(),
                    color = R.color.blue_2E76EE.toComposeColor(),
                )
            }
        }
    }
}